package cn.wit.summit.chwan.ui.activity;

import android.content.Intent;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.text.Editable;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextWatcher;
import android.text.style.ForegroundColorSpan;
import android.text.style.StyleSpan;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import org.greenrobot.eventbus.EventBus;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.wit.summit.chwan.R;
import cn.wit.summit.chwan.models.dto.CfgExplainBean;
import cn.wit.summit.chwan.models.event.DeleteOrModifyCommentEvent;
import cn.wit.summit.chwan.models.request.CreateCommentRequest;
import cn.wit.summit.chwan.models.request.EditCommentRequest;
import cn.wit.summit.chwan.models.request.GetCommentTokenRequest;
import cn.wit.summit.chwan.models.response.CodeloginRespone;
import cn.wit.summit.chwan.models.response.CreateCommentResponse;
import cn.wit.summit.chwan.models.response.GetCommentTokenResponse;
import cn.wit.summit.chwan.models.response.ResponseBase;
import cn.wit.summit.chwan.retrofit.ApiUtil;
import cn.wit.summit.chwan.retrofit.MyCallback;
import cn.wit.summit.chwan.retrofit.RetrofitManager;
import cn.wit.summit.chwan.ui.base.MyActivity;
import cn.wit.summit.chwan.ui.base.MyApplication;
import cn.wit.summit.chwan.utils.AESUtils;
import cn.wit.summit.chwan.utils.AccountBean;
import cn.wit.summit.chwan.utils.AccountUtil;
import cn.wit.summit.chwan.utils.IntentUtil;
import cn.wit.summit.chwan.utils.NetWorkUtils;
import cn.wit.summit.chwan.utils.PreferenceUtil;
import cn.wit.summit.chwan.utils.StringUtils;
import cn.wit.summit.chwan.widgets.AddNickDialog;
import cn.wit.summit.chwan.widgets.MStarBar;
import retrofit2.Retrofit;

/**
 * 创建点评
 * Created by tangbl on 2017/9/6.
 */
public class CommentCreatActivity extends MyActivity {

    @Bind(R.id.mstarBar)
    MStarBar mstarBar;
    @Bind(R.id.mstarBarTx)
    TextView mstarBarTx;
    @Bind(R.id.phoneModleCB)
    CheckBox phoneModleCB;
    @Bind(R.id.starLl)
    LinearLayout starLl;
    @Bind(R.id.bottomRuleLl)
    LinearLayout bottomRuleLl;
    @Bind(R.id.commentcreat_et)
    EditText commentcreatEt;
    @Bind(R.id.bottomRuleRl)
    RelativeLayout bottomRuleRl;

    private TextView mBarRightTx;

    private String commentId;
    private String commentContent;
    private float commentStars;
    private String gameId;
    private String gameType;
    private int gameIsStart;
    private String packageName;
    private boolean isEdit;
    private String phoneModel;
    private String commentScoreSwitch;//星星开关 1：开，0：关
    private int bespeakSwitch;//是否是预约游戏 1：开，0：关

    private String comentToken = "-1";
    private String content;
    private String uId;
    private String uToken;
    private String uHeadUrl;
    private String uName;

    private AddNickDialog addNickDialog;

    private RetrofitManager retrofitManager;
    private Retrofit retrofitComment;
    private ApiUtil apiComment;
    private Retrofit retrofitLogin;
    private ApiUtil apiLogin;

    private CfgExplainBean listRule;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_comment_creat);
        ButterKnife.bind(this);

        retrofitManager = RetrofitManager.getInstance(mContext);
        retrofitComment = retrofitManager.getCommentRetrofit();
        apiComment = retrofitComment.create(ApiUtil.class);
        retrofitLogin = retrofitManager.getLoginRetrofit();
        apiLogin = retrofitLogin.create(ApiUtil.class);

        showRule();
        initData();
        initView();
    }

    private void showRule() {
        listRule = MyApplication.arrayCommentExplain;
        if (listRule==null || StringUtils.isEmpty(listRule.getExplain())) {
            bottomRuleRl.setVisibility(View.GONE);
            return;
        }

        bottomRuleRl.setVisibility(View.VISIBLE);

        bottomRuleLl.removeAllViews();
//        String[] text = getResources().getStringArray(R.array.create_comment_rule_list);
        String[] text = listRule.getExplain().split("<br />");
        for(int i=0;i<text.length;i++) {
            View view = LayoutInflater.from(mContext).inflate(R.layout.item_rule_view,null, false);
            TextView itemRuleOneTx = view.findViewById(R.id.itemRuleOneTx);
            TextView itemRuleTwoTx = view.findViewById(R.id.itemRuleTwoTx);

            itemRuleOneTx.setText((i+1)+"、");

            String temp = text[i];
            if (temp.contains("给予") && temp.contains("元")) {
                int numS = temp.indexOf("给予");
                int numE = temp.indexOf("元");

                SpannableString spannableString = new SpannableString(temp);
                //设置颜色
                spannableString.setSpan(new ForegroundColorSpan(Color.parseColor("#000000")), numS+2, numE+1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                //设置字体，BOLD为粗体
                spannableString.setSpan(new StyleSpan(android.graphics.Typeface.BOLD), numS+2, numE+1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);

                itemRuleTwoTx.setText(spannableString);
            } else {
                itemRuleTwoTx.setText(temp);
            }
            if (i>0) {
                LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
                params.topMargin = (int) getResources().getDimension(R.dimen.wdp17);
                view.setLayoutParams(params);
            }

            bottomRuleLl.addView(view);
        }
    }

    private void initView() {
        if (isEdit) {
            setBarTitleTx(R.string.comment_edit_title_str);
        } else {
            setBarTitleTx(R.string.comment_create_title_str);
        }
        mBarRightTx = setBarRightTx(getResources().getString(R.string.comment_all_right_str));
        mBarRightTx.setBackgroundResource(R.drawable.selector_commit_bg);
        mBarRightTx.setTextColor(Color.parseColor("#bfffffff"));
        mBarRightTx.setTextSize(TypedValue.COMPLEX_UNIT_PX, getResources().getDimension(R.dimen.wdp28));
        mBarRightTx.setEnabled(false);
        mBarRightTx.setOnClickListener(null);
        commentcreatEt.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                String str = s.toString().trim();
                if (StringUtils.isEmpty(str) || str.length() < 3 || str.length() > 3000) {
                    mBarRightTx.setTextColor(Color.parseColor("#bfffffff"));
                    mBarRightTx.setEnabled(false);
                    mBarRightTx.setOnClickListener(null);
                } else {
                    mBarRightTx.setTextColor(Color.parseColor("#43BEFE"));
                    mBarRightTx.setEnabled(true);
                    mBarRightTx.setOnClickListener(new TopRightClickListener());
                }
            }
        });
        commentcreatEt.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) {
                    commentcreatEt.setHint("");
                } else {
                    commentcreatEt.setHint(R.string.comment_create_hint);
                }
            }
        });

        //是否有星星评分
        if (commentScoreSwitch != null && commentScoreSwitch.equals("1")) {
            starLl.setVisibility(View.VISIBLE);
        } else {
            starLl.setVisibility(View.GONE);
        }

        //修改评论
        if (commentContent != null) {
            commentcreatEt.setText(commentContent);
        }
        mstarBar.setStarMark(commentStars);

        String modelStr = getSystemModel();
        if (modelStr != null && !modelStr.isEmpty())
            phoneModleCB.setText(modelStr);
        else
            showToast(getResources().getString(R.string.comment_phone_fail_str));

        if (isEdit) {
            if (phoneModel != null && !phoneModel.isEmpty()) {
                phoneModleCB.setChecked(true);
            } else {
                phoneModleCB.setChecked(false);
            }
        } else {
            phoneModleCB.setChecked(true);
        }
    }

    private void initData() {
        Intent intent = getIntent();
        commentId = intent.getStringExtra("commentId");
        commentContent = intent.getStringExtra("commentContent");
        gameId = intent.getStringExtra("gameId");
        gameType = intent.getStringExtra("gameType");
        packageName = intent.getStringExtra("packageName");
        phoneModel = intent.getStringExtra("phoneModel");
        commentScoreSwitch = intent.getStringExtra("commentScoreSwitch");
        commentStars = intent.getFloatExtra("commentStars", 0f);
        gameIsStart = intent.getIntExtra("gameIsStart", 0);
        bespeakSwitch = intent.getIntExtra("bespeakSwitch", 0);
        isEdit = intent.getBooleanExtra("isEdit", false);

        comentToken = PreferenceUtil.getPreferences(mContext, PreferenceUtil.PRE_COMMENT_TOKEN);
    }

    @Override
    protected void onResume() {
        super.onResume();
        //是否登陆
        if (AccountUtil.getInstance().getUid() == 0) {
            IntentUtil.getInstance().goLoginActivity(mContext);
            return;
        }
    }

    /**
     * 获取手机型号
     *
     * @return 手机型号
     */
    public static String getSystemModel() {
        return Build.MODEL;
    }

    private void createCommentSuccess(boolean isEdit, float starNum, String str, String upPhoneModel) {
        if (isEdit) {
            postEvent(2, starNum, str, upPhoneModel);
            showToast(getResources().getString(R.string.comment_modify_succ));
        } else {
            postEvent(0, starNum, str, upPhoneModel);
            showToast(getResources().getString(R.string.comment_succ));
        }
        hideSoftInput(commentcreatEt);
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                finish();
            }
        }, 200);
    }

    private void postEvent(int type, double starNum, String str, String upPhoneModel) {
        EventBus.getDefault().post(new DeleteOrModifyCommentEvent(type, str, starNum
                , System.currentTimeMillis() / 1000, upPhoneModel));
    }

    @OnClick({R.id.chenckMoreRuleTx})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.chenckMoreRuleTx:
                if (listRule!=null && !StringUtils.isEmpty(listRule.getUrl())) {
                    IntentUtil.getInstance().goShareWebActivity(mContext, listRule.getUrl());
                }
                break;
        }
    }

    private class TopRightClickListener implements View.OnClickListener {

        @Override
        public void onClick(View v) {
            AccountBean accountBean = AccountUtil.getInstance().getAccountData();
            if (accountBean == null) {//未登录
                IntentUtil.getInstance().goLoginActivity(CommentCreatActivity.this);
                return;
            }

            uId = AccountUtil.getInstance().getUid() + "";
            uToken = AccountUtil.getInstance().getToken();
            uHeadUrl = AccountUtil.getInstance().getAccountData().getAvatar();
            uName = AccountUtil.getInstance().getAccountData().getNickname();

            content = commentcreatEt.getText().toString().trim();
            if (content.length() < 3 || content.length() > 800) {
                showToast(getResources().getString(R.string.comment_sub_str));
                return;
            }

            if (accountBean.getDefaultNickname() == 0) {
                addNickDialog = new AddNickDialog(mContext);
                addNickDialog.show();
                addNickDialog.setMsg(uName);
                addNickDialog.setCancleBtn(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        addNickDialog.dismiss();
                        hideSoftInput(addNickDialog.getCurrencyPromptNickEt());
                    }
                });
                addNickDialog.setOkBtn(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        hideSoftInput(addNickDialog.getCurrencyPromptNickEt());
                        String strNick = addNickDialog.getNick();
                        if (StringUtils.isEmpty(strNick)) {
                            showToast(mContext.getResources().getString(R.string.dialog_add_nick_wran));
                            return;
                        }
                        if (!StringUtils.matchStringLength(strNick, 4, 16)) {
                            showToast("昵称格式有误，输入4至16位字母或2至8汉字");
                            return;
                        }
                        modifyNick(strNick);
                    }
                });
                hideSoftInput(commentcreatEt);
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        //设置可获得焦点
                        addNickDialog.getCurrencyPromptNickEt().setFocusable(true);
                        addNickDialog.getCurrencyPromptNickEt().setFocusableInTouchMode(true);
                        //请求获得焦点
                        addNickDialog.getCurrencyPromptNickEt().requestFocus();
                        showSoftInput(addNickDialog.getCurrencyPromptNickEt());
                    }
                }, 200);
                return;
            }

            hideSoftInput(commentcreatEt);

            comentToken = PreferenceUtil.getPreferences(mContext, PreferenceUtil.PRE_COMMENT_TOKEN);
            if (StringUtils.isEmpty(comentToken) || comentToken.equals("-1")) {
                getCommentToken();
            } else {
                toCreateComment();
            }
        }
    }

    /**
     * 上传网名
     */
    private void modifyNick(final String na) {
        if (NetWorkUtils.isNetworkConnected(CommentCreatActivity.this)) {
            showLoading("修改中...");
            int uid = MyApplication.accountBean.getUid();
            String token = MyApplication.accountBean.getToken();

            apiLogin.modifyNick(na, uid + "", token).enqueue(new MyCallback<ResponseBase<CodeloginRespone>>() {
                @Override
                public void onSuccess(ResponseBase<CodeloginRespone> model) {
                    showToast("修改成功");
                    AccountBean bean = MyApplication.accountBean;
                    bean.setNickname(na);
                    bean.setDefaultNickname(1);
                    AccountUtil.getInstance().saveAccountData(bean);
                    if (addNickDialog != null && addNickDialog.isShowing())
                        addNickDialog.dismiss();
                    cancelLoading();
                }

                @Override
                public void onFailure(int code, String msg) {
                    showToast(msg);
                    cancelLoading();
                }
            });
        } else {
            showToast("网络连接失败，再试试吧~");
            cancelLoading();
        }
    }

    private void getCommentToken() {
        GetCommentTokenRequest tempRequest = retrofitManager.getCommentTokenRequest();
        apiComment.getCommentToken(tempRequest).enqueue(new MyCallback<ResponseBase<GetCommentTokenResponse>>() {
            @Override
            public void onSuccess(ResponseBase<GetCommentTokenResponse> model) {
                GetCommentTokenResponse data = model.getData_info();
                String token = AESUtils.encrypt4Comment(data.getToken() + "|" + data.getTimes());
                comentToken = token;
                PreferenceUtil.savePreference(mContext, PreferenceUtil.PRE_COMMENT_TOKEN, token);
                PreferenceUtil.saveLongPreference(mContext, PreferenceUtil.PRE_COMMENT_TOKEN_TIME, data.getTimes());
                toCreateComment();
            }

            @Override
            public void onFailure(int code, String msg) {
                PreferenceUtil.savePreference(mContext, PreferenceUtil.PRE_COMMENT_TOKEN, "-1");
                showToast(msg);
            }
        });
    }

    private void toCreateComment() {
        if (isEdit) {//编辑
            EditCommentRequest editCommentRequest = retrofitManager.editCommentRequest(comentToken, gameId, uId, uToken, content, commentId, phoneModleCB.isChecked());
            apiComment.editComment(editCommentRequest).enqueue(new MyCallback<ResponseBase<CreateCommentResponse>>() {
                @Override
                public void onSuccess(ResponseBase<CreateCommentResponse> model) {
                    CreateCommentResponse data = model.getData_info();
                    if (data != null && data.getAdd_comment_energy() > 0 && !isEdit) {
                        MyApplication.commentAddEnergy = data.getAdd_comment_energy();
                    }
                    createCommentSuccess(isEdit, 0, content, phoneModleCB.isChecked() ? phoneModleCB.getText().toString() : "");
                }

                @Override
                public void onFailure(int code, String msg) {
                    if (code == 801) {
                        PreferenceUtil.savePreference(mContext, PreferenceUtil.PRE_COMMENT_TOKEN, "-1");
                        getCommentToken();
                    }
                    showToast(msg);
                }
            });
        } else {
            CreateCommentRequest createCommentRequest = retrofitManager.createCommentRequest(comentToken, gameId, uId, uToken, uHeadUrl, uName, content, phoneModleCB.isChecked());
            apiComment.createComment(createCommentRequest).enqueue(new MyCallback<ResponseBase<CreateCommentResponse>>() {
                @Override
                public void onSuccess(ResponseBase<CreateCommentResponse> model) {
                    CreateCommentResponse data = model.getData_info();
                    if (data != null && data.getAdd_comment_energy() > 0 && !isEdit) {
                        MyApplication.commentAddEnergy = data.getAdd_comment_energy();
                    }
                    createCommentSuccess(isEdit, 0, content, phoneModleCB.isChecked() ? phoneModleCB.getText().toString() : "");
                }

                @Override
                public void onFailure(int code, String msg) {
                    if (code == 801) {
                        PreferenceUtil.savePreference(mContext, PreferenceUtil.PRE_COMMENT_TOKEN, "-1");
                        getCommentToken();
                    }
                    showToast(msg);
                }
            });
        }
    }
}
